package com.mc.code.web;

import com.mc.code.entity.CodeItems;
import com.mc.code.entity.CodeUsers;
import com.mc.code.service.ItemsService;
import com.mc.code.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("item")
public class ItemsController {

    @Autowired
    private ItemsService itemsService;
    @Autowired
    private UsersService usersService;



    //    未登录时查看项目列表
    @RequestMapping("/itemsList")
    public String itemsList(Model model) {
        List<CodeItems> codeItems = itemsService.items(1);
        System.out.println("未登录时的项目列表:" + codeItems);
        model.addAttribute("codeItems", codeItems);
        return "itemsList";
    }


    //查看项目详情
    @RequestMapping("/itemDetails")
    public String itemDetails(Model model, Integer itemNo, String userNo,HttpServletRequest request) {
        List<CodeItems> codeItemsDetails = itemsService.itemsDetails(itemNo);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        Integer collectionItemNo=itemsService.collection(Integer.parseInt(userNo),itemNo);
        int condition=0;
        if(collectionItemNo == null)
            condition = 1;
       else  if(collectionItemNo == itemNo)
           condition = 0;
        model.addAttribute("condition",condition);
        Integer collectionNum=itemsService.collectionNum(itemNo);
        System.out.println(collectionNum+"收藏数");
        model.addAttribute("collectionNum",collectionNum);
        model.addAttribute("itemNo",codeItemsDetails.get(0).getItemNo());
        model.addAttribute("codeUsers", codeUsers);
        model.addAttribute("itemsDetails", codeItemsDetails);
        return "itemDetails";
    }

    //未登录查看项目详情
    @RequestMapping("/outItemDetails")
    public String outItemDetails(Model model, Integer itemNo) {
        List<CodeItems> codeItemsDetails = itemsService.itemsDetails(itemNo);
        Integer collectionNum=itemsService.collectionNum(itemNo);
        System.out.println(collectionNum+"收藏数");
        model.addAttribute("collectionNum",collectionNum);
        model.addAttribute("itemsDetails", codeItemsDetails);
        return "outItemDetails";
    }

    //    登录后查看项目列表
    @RequestMapping("/loginItemsList")
    public String loginItemsList(Model model, String userNo) {
        List<CodeItems> codeItems = itemsService.items(1);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        System.out.println(codeUsers);
        model.addAttribute("codeUsers", codeUsers);
        model.addAttribute("codeItems", codeItems);
        return "loginItemsList";
    }

    //    需求方发布项目前往发布项目页面
    @RequestMapping("/releaseProject")
    public String releaseProject(Model model, String userNo) {
        System.out.println("项目发布人编号是:" + userNo);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        return "releaseProject";
    }


//取消收藏
@RequestMapping("/delCollection")
public String delCollection(Model model, int itemNo, String userNo,HttpServletRequest request) {
    List<CodeItems> codeItemsDetails = itemsService.itemsDetails(itemNo);
    List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
    itemsService.delCollection(itemNo,Integer.parseInt(userNo));
    Integer collectionItemNo=itemsService.collection(Integer.parseInt(userNo),itemNo);
    int condition=0;
    if(collectionItemNo == null)
        condition = 1;
    else  if(collectionItemNo == itemNo)
        condition = 0;
    model.addAttribute("condition",condition);
   /* int stageNum = 0;
    int stageTotal = 0;
    stageNum = itemsService.itemsStageNum(itemNo);
    stageTotal = itemsService.itemsTotalNum(itemNo);
    if (stageNum == 0)
        codeItemsDetails.get(0).setItemDid(1);
    else if (stageNum > 0 && stageNum <= stageTotal)
        codeItemsDetails.get(0).setItemDid(2);
    else codeItemsDetails.get(0).setItemDid(3);*/
    Integer collectionNum=itemsService.collectionNum(itemNo);
    System.out.println(collectionNum+"收藏数");
    model.addAttribute("collectionNum",collectionNum);
    model.addAttribute("itemNo",codeItemsDetails.get(0).getItemNo());
    model.addAttribute("codeUsers", codeUsers);
    model.addAttribute("itemsDetails", codeItemsDetails);
    return "itemDetails";
}



    //收藏项目
    @RequestMapping("/addCollection")
    public String addCollection(Model model, int itemNo, String userNo,HttpServletRequest request) {
        List<CodeItems> codeItemsDetails = itemsService.itemsDetails(itemNo);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        itemsService.delCollection(itemNo,Integer.parseInt(userNo));
        itemsService.addCollection(itemNo,Integer.parseInt(userNo));
        Integer collectionItemNo=itemsService.collection(Integer.parseInt(userNo),itemNo);
        int condition=0;
        if(collectionItemNo == null)
            condition = 1;
        else  if(collectionItemNo == itemNo)
            condition = 0;
        model.addAttribute("condition",condition);
      /*  int stageNum = 0;
        int stageTotal = 0;
        stageNum = itemsService.itemsStageNum(itemNo);
        stageTotal = itemsService.itemsTotalNum(itemNo);
        if (stageNum == 0)
            codeItemsDetails.get(0).setItemDid(1);
        else if (stageNum > 0 && stageNum <= stageTotal)
            codeItemsDetails.get(0).setItemDid(2);
        else codeItemsDetails.get(0).setItemDid(3);*/
        Integer collectionNum=itemsService.collectionNum(itemNo);
        System.out.println(collectionNum+"收藏数");
        model.addAttribute("collectionNum",collectionNum);
        model.addAttribute("itemNo",codeItemsDetails.get(0).getItemNo());
        model.addAttribute("codeUsers", codeUsers);
        model.addAttribute("itemsDetails", codeItemsDetails);
        return "itemDetails";
    }










    //发布成功
    @RequestMapping(value = "/releaseProject1", method = {RequestMethod.POST})
    public String releaseProject1(HttpServletRequest request, Model model,  String userNo) throws IOException {
//        定义项目对象
        CodeItems codeItems = new CodeItems();
//        定义用户对象
        CodeUsers codeUsers = new CodeUsers();

        System.out.println("发布项目后的userNo" + userNo);
//        用户编号
        int promulgatorId = Integer.parseInt(userNo);
//        项目类型
        int itemType = Integer.parseInt(request.getParameter("project"));
        System.out.println(itemType);
//        项目编号
        int itemNo = itemsService.itemsEndNo() + 1;
        System.out.println(itemNo);
//        项目名称
        String itemName = request.getParameter("itemName");
//        期望交付周期
        int day = Integer.parseInt(request.getParameter("day"));
//        项目预算
        double money = Double.parseDouble(request.getParameter("money"));
//项目描述
        String text = request.getParameter("text");
//        招募要求
        String itemNeedText = request.getParameter("itemNeedText");
//        联系邮箱
        String email = request.getParameter("email");
//联系手机号
        String phoneNum = request.getParameter("phoneNum");

        int needType= Integer.parseInt(request.getParameter("needType"));
//塞入项目信息
        codeItems.setPromulgatorId(promulgatorId);//塞入发布人编号
        codeItems.setItemType(itemType);
        codeItems.setItemNo(itemNo);
        codeItems.setItemName(itemName);
        codeItems.setDay(day);
        codeItems.setMoney(money);
        codeItems.setText(text);
        codeItems.setItemNeedText(itemNeedText);
//        项目审核状态和开始状态
        codeItems.setItemCondition(1);
        codeItems.setItemDid(1);
        codeItems.setItemNeedType(needType);


//        文件上传
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                String pa="E:/inno/ideaIUWorkSpace/pic/";
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                System.out.println(file.getOriginalFilename());
                if(file!=null) {
                    String path = file.getOriginalFilename();
                    //找到.的下标
                    int begin = path.indexOf(".");
                    //找到字符串末位下标，即字符串长度
                    int last = path.length();
                    //反向找到第一个\
                    int xg = path.lastIndexOf("\\");
                    String str = null;
                    if (begin != -1) {
                        str = path.substring(begin);
                    }
                    System.out.println("判断文件是啥：" + str);
//                    图片格式有：BMP、JPG、JPEG、PNG、GIF。
                    if (str != null) {
                        if (str.equals(".jpg") || str.equals(".gif") || str.equals(".png")) {
                            String img = UUID.randomUUID()+path.substring(begin, last);
                            codeItems.setItemImage(img);
                            System.out.println(codeItems);
                            String newPath=pa+img;
                            //上传
                            file.transferTo(new File(pa+img));
                        } else {
                            String fileName = UUID.randomUUID()+path.substring(begin, last);
                            codeItems.setDemandDocument(fileName);
                            //上传
                            file.transferTo(new File(pa+fileName));
                        }
                    }
                }
            }

            //    插入数据库
            itemsService.releaseProject(codeItems);
        }

//        更新用户联系方式
        codeUsers.setUserNo(Integer.parseInt(userNo));
        codeUsers.setPhoneNum(phoneNum);
        codeUsers.setEmail(email);
        usersService.updateContact(codeUsers);

        List<CodeUsers> codeUsers1 = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers",codeUsers1);
        List<CodeItems> codeItems1=itemsService.items(1);
        model.addAttribute("codeItems",codeItems1);
        return "loginItemsList";
    }


//    下载文件
//文件下载相关代码
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response,String downFile,int itemNo) {
    String fileName = downFile;// 设置文件名，根据业务需要替换成要下载的文件名
    if (fileName != null) {
        //设置文件路径
        String realPath = "E://inno//ideaIUWorkSpace//pic//";
        File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return null;
}

//查看我的收藏
@RequestMapping("myCollection")
public String myCollection(Model model,String userNo){
        List<CodeUsers> codeUsers=usersService.codeUsers(userNo);
    List<CodeItems> collectItems=itemsService.collectItems(userNo);
    List<String> nickname=new ArrayList<>();
    int i=0;
    while (i++<collectItems.size())
        {
            nickname.add(usersService.nickName(collectItems.get(0).getPromulgatorId()));
        }
        model.addAttribute("nickName",nickname);
        model.addAttribute("codeUsers",codeUsers);
        model.addAttribute("collectItems",collectItems);
        return "collectionProjects";
}







}